import { reactive, defineComponent, ref, resolveComponent, DefineComponent } from 'vue'
import { StatisticsRankList, StatisticsRankItem } from '@/components/statistics-rank'

import { usePage } from '@/hook/page'
import { numberToPercentage } from '@/utils'

function request(param: RequestPagination): Promise<ResponseList<number>> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ list: [1, 2, 3], total: 100, page: 10 })
    }, 500)
  })
}

export default defineComponent({
  name: 'AppList',
  setup() {
    const form = reactive({ name: '' })
    const formRef = ref<HTMLFormElement | null>(null)
    const page = usePage({ request }, form)

    const ascend = reactive([
      {
        userId: '6914454480564711449',
        userName: 'supermarket01',
        afterSalesRate: 0.0714
      },
      {
        userId: '6914521132597702779',
        userName: 'supermarket04',
        afterSalesRate: 0.3141
      },
      {
        userId: '6914768472147423300',
        userName: 'supermarket05',
        afterSalesRate: 0
      }
    ])

    return {
      ascend,
      formRef,
      form,
      page
    }
  },
  render() {
    const AppPage = resolveComponent('app-page') as DefineComponent

    return (
      <AppPage
        v-slots={{
          header: () => (
            <form action='javascript:;' ref='formRef'>
              <h1>{this.form.name}</h1>
              <input type='text' v-model_trim={this.form.name} name='title' />
              <button type='button' onClick={() => this.page.search()}>
                搜索
              </button>
              <button type='button' onClick={() => this.page.resetForm(this.formRef!)}>
                重置
              </button>
            </form>
          )
        }}>
        <StatisticsRankList title='排行榜'>
          {this.ascend.map((item, index) => (
            <StatisticsRankItem
              index={index}
              v-slots={{
                label: () => item.userName,
                value: () => numberToPercentage(item.afterSalesRate, true)
              }}
            />
          ))}
        </StatisticsRankList>
      </AppPage>
    )
  }
})
